import React, { useRef, useState } from 'react';
import './huabi.css'
const Huabi = () => {
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const [isDrawing, setIsDrawing] = useState(false);
    const startDrawing = () => {
        setIsDrawing(true);
        // 可以在这里添加额外的初始化代码  
    };
    const stopDrawing = () => {
        setIsDrawing(false);
        // 可以在这里添加清理代码  
    };
    const handleMouseDown = (e: React.MouseEvent<HTMLCanvasElement, MouseEvent>) => {
        if (!isDrawing) return;
        const canvas = canvasRef.current;
        if (!canvas) return;

        const ctx: any = canvas.getContext('2d');
        ctx.beginPath();
        ctx.moveTo(e.nativeEvent.offsetX, e.nativeEvent.offsetY);

        function draw(e: MouseEvent) {
            if (!isDrawing) return;
            ctx.lineTo(e.offsetX, e.offsetY);
            ctx.stroke();
            ctx.moveTo(e.offsetX, e.offsetY);
        }

        function stopDrawingLocal() {
            document.removeEventListener('mousemove', draw);
            document.removeEventListener('mouseup', stopDrawingLocal);
        }

        document.addEventListener('mousemove', draw);
        document.addEventListener('mouseup', stopDrawingLocal);
    };
    return (
        <div className='huada'>
            <canvas  className='hua'
                ref={canvasRef}
                width="300"
                height="300"
                onMouseDown={handleMouseDown}
                style={{ border: '1px solid black' }} 
            />
            <button onClick={startDrawing} >开始绘制</button>
            <button onClick={stopDrawing} >停止绘制</button>
        </div>
    )
}

export default Huabi
